package com.huajin.iot.system.controller;

import com.huajin.iot.common.annotation.Log;
import com.huajin.iot.common.config.Constant;
import com.huajin.iot.common.controller.BaseController;
import com.huajin.iot.common.domain.Tree;
import com.huajin.iot.common.utils.R;
import com.huajin.iot.system.domain.MenuDO;
import com.huajin.iot.system.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bootdo 1992lcg@163.com
 */
@Api(tags = {"菜单管理接口"})
@RequestMapping("/sys/menu")
@RestController
public class MenuController extends BaseController {
    @Autowired
    MenuService menuService;


    @ApiOperation("菜单列表")
//    @RequiresPermissions("sys:menu:menu")
    @PostMapping("/list")
    @ResponseBody
    R list(@RequestParam Map<String, Object> params) {
        List<MenuDO> menus = menuService.list(params);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", menus);
        return R.ok(resultMap);
    }

    @ApiOperation("新增菜单")
    @Log("新增菜单")
    @RequiresPermissions("sys:menu:add")
    @PostMapping("/save")
    @ResponseBody
    R save(MenuDO menu) {
        if (menuService.save(menu) > 0) {
            return R.ok();
        } else {
            return R.error(1, "保存失败");
        }
    }

    @ApiOperation("更新菜单")
    @Log("更新菜单")
    @RequiresPermissions("sys:menu:edit")
    @PostMapping("/update")
    @ResponseBody
    R update(MenuDO menu) {
        if (menuService.update(menu) > 0) {
            return R.ok();
        } else {
            return R.error(1, "更新失败");
        }
    }

    @ApiOperation("删除一个菜单")
    @Log("删除一个菜单")
    @RequiresPermissions("sys:menu:remove")
    @PostMapping("/remove")
    @ResponseBody
    R remove(Long id) {
        if (menuService.remove(id) > 0) {
            return R.ok();
        } else {
            return R.error(1, "删除失败");
        }
    }

    @ApiOperation("菜单列表")
    @GetMapping("/tree")
    @ResponseBody
    R tree() {
        Tree<MenuDO> tree = menuService.getTree();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("tree", tree);
        return R.ok(resultMap);
    }

    @ApiOperation("某角色对应的菜单列表")
    @GetMapping("/tree/{roleId}")
    @ResponseBody
    R tree(@PathVariable("roleId") Long roleId) {
        Tree<MenuDO> tree = menuService.getTree(roleId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("tree", resultMap);
        return R.ok(resultMap);
    }
}
